#!/bin/bash

set -e          # exit on error
set -o pipefail # exit on pipeline error
set -u          # treat unset variable as error

. /minioslib || exit 1

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
APP="code"
APP_NAME="Visual Studio Code"
APP_EXECUTABLE="code"
APP_MODULE_NUMBER="6"

wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor >packages.microsoft.gpg
install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
sh -c 'echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/trusted.gpg.d/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main" >/etc/apt/sources.list.d/vscode.list'
rm -f packages.microsoft.gpg

# install packages
pkg update
pkg install code

if grep slax /etc/hostname >/dev/null; then
    cat <<EOF >/usr/bin/fblive-add-$APP.sh
#!/bin/bash
if [ -f /var/cache/fblive-add-$APP.addon ]; then
    if ! grep $APP_EXECUTABLE /usr/bin/fbliveapp >/dev/null; then
        cp /usr/bin/fbliveapp /usr/bin/fbliveapp.$APP.bak
        sed -i "/shift/ e cat /var/cache/fblive-add-$APP.addon" /usr/bin/fbliveapp
        sed -i 's,exec "\$EXECUTABLE" "\$@",exec "\$EXECUTABLE" \$ARGS "\$@",g' /usr/bin/fbliveapp
        #rm /var/cache/fblive-add-$APP.addon
        if [ -f /usr/share/applications/$APP.desktop ]; then
            rm /usr/share/applications/$APP.desktop
        fi
    fi
fi

EOF
    chmod +x /usr/bin/fblive-add-$APP.sh
    cat <<EOF >/usr/lib/systemd/system/fblive-add-$APP.service
[Unit]
Description=Adding $APP_NAME to fbliveapp
#After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/fblive-add-$APP.sh
RemainAfterExit=true
ExecStop=
StandardOutput=journal

[Install]
WantedBy=multi-user.target

EOF
    cat <<EOF >/usr/share/applications/$APP_MODULE_NUMBER$APP.desktop
[Desktop Entry]
Version=1.0
Name=$APP_NAME
GenericName=$APP_NAME
Exec=fbliveapp $APP %U
Terminal=false
X-MultipleArgs=false
Type=Application
Icon=$APP.png
Categories=Network;WebBrowser;
MimeType=audio/*;image/*;video/*;application/pdf;application/x-pdf;text/html;text/xml;application/xhtml_xml;application/x-mimearchive;x-scheme-handler/http;x-scheme-handler/https;
StartupWMClass=$APP
StartupNotify=true

EOF
    cat <<EOF >/var/cache/fblive-add-$APP.addon
if [ "\$1" = "$APP" ]; then
   NAME="$APP_NAME"
   EXECUTABLE="/usr/bin/$APP_EXECUTABLE"
   ARGS="--no-sandbox --user-data-dir ~/.vscode"
   GUEST=true
fi

EOF
    systemctl enable fblive-add-$APP.service
fi

PACKAGE=$APP_EXECUTABLE
echo "PACKAGE=$PACKAGE" >/.package
echo "VERSION=$(dpkg -s $PACKAGE | grep Version | sed 's/Version: //g' | sed 's/:/-/g')" >>/.package
